﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using CustomWindow;
using System.Windows.Forms;

namespace HomeMediaBrowser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : StandardWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            IsServer = false;
            string Mode = App.CommandLineArgs["-Mode"] as string;
            if (Mode == "Server")
                IsServer = true;
            else if (Mode == "Client")
                IsServer = false;

            AddHandler(GoogleLoginPage.LoginEvent, new System.Windows.RoutedEventHandler(OnLogin));
            AddHandler(MainPanel.PlayEvent, new System.Windows.RoutedEventHandler(OnPlay_MediaPlayer));
            AddHandler(MainPanel.PlayURLEvent, new System.Windows.RoutedEventHandler(OnPlayURL_MediaPlayer));

            TabUser.AddHandler(TabBorder.CloseEvent, new System.Windows.RoutedEventHandler(OnLogout));
            TabUser.AddHandler(TabBorder.SelectEvent, new System.Windows.RoutedEventHandler(OnTabUser));

            TabPlay.AddHandler(TabBorder.CloseEvent, new System.Windows.RoutedEventHandler(OnClosePlay));
            TabPlay.AddHandler(TabBorder.SelectEvent, new System.Windows.RoutedEventHandler(OnTabPlay));
            TabPlay.HideTab();
            
            SelectTabUser();

            WindowHeightAnimation = 120;

            //DefaultLogin();
        }

        void SelectTabUser()
        {
            TabUser.IsSelected = true;
            TabPlay.IsSelected = false;
        }
        void SelectTabPlay()
        {
            TabUser.IsSelected = false;
            TabPlay.IsSelected = true;
        }
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
            try
            {
                SetDwmWindowHook(hwnd.ToInt32());
                AeroHelper.ExtendGlassFrame(this, new Thickness(-1));
                SetWindowThemeAttribute(this, false, false);
            }
            catch (Exception Ex)
            {
                MainCanvas.Background = Brushes.White;
                MainCanvasBorder.Visibility = Visibility.Visible;
            }

        }
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            IntPtr lRet = IntPtr.Zero;
            switch (msg)
            {
                case WM_NCCALCSIZE:
                    if (wParam.ToInt32() == TRUE)
                        handled = true;
                    break;
                case WM_NCHITTEST:
                    lRet = HitTest(hwnd, lParam.ToInt32());
                    if (lRet.ToInt32() != HTNOWHERE)
                        handled = true;
                    break;
            }
            return lRet;
        }
        public static Int32 GET_X_LPARAM(int lParam)
        {
            return (lParam & 0xffff);
        }
        public static Int32 GET_Y_LPARAM(int lParam)
        {
            return (lParam >> 16);
        }
        public const int BOTTOMEXTENDWIDTH = 5;
        public const int TOPEXTENDWIDTH = 35;
        public const int LEFTEXTENDWIDTH = 5;
        public const int RIGHTEXTENDWIDTH = 5;
        public const int TOPBUTTONWIDTH = 110;

        private IntPtr HitTest(IntPtr hWnd, int lParam)
        {
            Point ptMouse;
            ptMouse.x = GET_X_LPARAM(lParam);
            ptMouse.y = GET_Y_LPARAM(lParam);
            tagRECT rcWindow = new tagRECT();
            GetWindowRect(hWnd, out rcWindow);

            // Get frame rectangle, adjusted for the style without a caption.
            tagRECT rcFrame = new tagRECT();
            AdjustWindowRectEx(ref rcFrame, WS_OVERLAPPEDWINDOW & ~WS_CAPTION, false, 0);

            // Determine if hit test is for resizing, default middle (1,1).
            ushort uRow = 1;
            ushort uCol = 1;
            bool fOnResizeBorder = false;
            // Determine if the point is at the top or bottom of the window.
            if (ptMouse.y >= rcWindow.top && ptMouse.y < rcWindow.top + TOPEXTENDWIDTH)
            {
                //temp do not allow border resize
                //fOnResizeBorder = (ptMouse.y < (rcWindow.top - rcFrame.top));
                uRow = 0;
            }
            else if (ptMouse.y < rcWindow.bottom && ptMouse.y >= rcWindow.bottom - BOTTOMEXTENDWIDTH)
            {
                uRow = 2;
            }

            // Determine if the point is at the left or right of the window.
            if (ptMouse.x >= rcWindow.left && ptMouse.x < rcWindow.left + LEFTEXTENDWIDTH)
            {
                uCol = 0; //left side
            }
            else if (ptMouse.x < rcWindow.right && ptMouse.x >= rcWindow.right - RIGHTEXTENDWIDTH)
            {
                uCol = 2; //right side
            }

            // Hit test (HTTOPLEFT, ... HTBOTTOMRIGHT)
            int[,] hitTests = new int[3, 3]
            {
                { HTTOPLEFT,    fOnResizeBorder ? HTTOP : HTCAPTION,    HTTOPRIGHT    },
                { HTLEFT,       HTNOWHERE,     HTRIGHT       },
                { HTBOTTOMLEFT, HTBOTTOM, HTBOTTOMRIGHT },
            };
            int ret = (hitTests[uRow, uCol]);

            //for min,max,restore,close button
            if (ret == HTCAPTION && ptMouse.x > rcWindow.right - (10 + 40 + 20 + 20))
                ret = HTNOWHERE;
            return (IntPtr)ret;

        }
        public virtual void OnLoaded(object sender, RoutedEventArgs e)
        {
            DefaultLogin();
        }

        public virtual void OnClosed(object sender, EventArgs e)
        {
            object cont = DownloadFrame.Content;
            DownloadPage Panel = cont as DownloadPage;
            if (Panel != null)
                Panel.UnLoaded();
        }       
        public virtual void OnLogin(object sender, RoutedEventArgs e)
        {
            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Visible;
            PlayFrame.Visibility = Visibility.Hidden;
            GoogleLoginPage Page = e.OriginalSource as GoogleLoginPage;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;
            TabUser.Text = Page.GetUserName();
            if (!IsServer)
                Panel.ServerIP = Page.m_strServerIP;
            else
                Panel.ServerIP = "http://127.0.0.1:8080/";
            Panel.InitServer(IsServer);

            if (IsServer)
                HideExpand();
            else
                ShowExpand();
        }
        public virtual void OnPlayURL_MediaPlayer(object sender, RoutedEventArgs e)
        {
            UIListItemData UIItem = e.OriginalSource as UIListItemData;
            if (UIItem == null || UIItem.Path == null)
                return;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;

            string path = Panel.ServerIP + "Download?path=" + UIItem.Path;
            path = Microsoft.JScript.GlobalObject.encodeURI(path); 
            IntPtr result = IntPtr.Zero;
            if (UIItem.Type == ThumbType.THUMB_VIDEO || UIItem.Type == ThumbType.THUMB_AUDIO)
                result = NativeMethods.ShellExecuteW((IntPtr)0, "open", "wmplayer.exe", path, null, 1 /* SW_SHOWNORMAL */);
            else
                new DownloadHelper(Panel, TaskType.TASK_DOWNLOADOPEN, UIItem.Path);
        }
        public virtual void OnPlay_MediaPlayer(object sender, RoutedEventArgs e)
        {
            UIListItemData UIItem = e.OriginalSource as UIListItemData;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;

            string pathItem = Panel.GetCachePath(UIItem.Path);
            string path = "\"" + pathItem + "\"";
            IntPtr result = IntPtr.Zero;
            if (UIItem.Type == ThumbType.THUMB_VIDEO || UIItem.Type == ThumbType.THUMB_AUDIO)
                result = NativeMethods.ShellExecuteW((IntPtr)0, "open", "wmplayer.exe", path, null, 1 /* SW_SHOWNORMAL */);
            else
                result = NativeMethods.ShellExecuteW((IntPtr)0, "open", "explorer", path, null, 1 /* SW_SHOWNORMAL */);

        }
        public virtual void OnPlayURL(object sender, RoutedEventArgs e )
        {
            UIListItemData UIItem = e.OriginalSource as UIListItemData;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;

            string szTemp = Encode64(UIItem.Path);
            szTemp = szTemp.Replace("+", "%2B");
            szTemp = szTemp.Replace("/", "%2F");
            szTemp = szTemp.Replace("=", "%3D");

            string path = Panel.ServerIP + "Download?path=" + szTemp;
          //  path = Microsoft.JScript.GlobalObject.escape(path); 
            MediaPlayerPage page = PlayFrame.Content as MediaPlayerPage;
            if (page == null)
                return;
            TabPlay.MaxWidth = page.Width;
            TabPlay.Text = UIItem.Name;
            SelectTabPlay();

            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Hidden;
            PlayFrame.Visibility = Visibility.Visible;
            page.play(path);
        }
        public virtual void OnPlay(object sender, RoutedEventArgs e)
        {
            UIListItemData UIItem = e.OriginalSource as UIListItemData;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;

            string path = Panel.GetCachePath(UIItem.Path);
            MediaPlayerPage page = PlayFrame.Content as MediaPlayerPage;
            if (page == null)
                return;
            TabPlay.MaxWidth = page.Width;
            TabPlay.Text = UIItem.Name;
            SelectTabPlay();

            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Hidden;
            PlayFrame.Visibility = Visibility.Visible;
            page.play(path);
        }

        public virtual void OnTabUser(object sender, RoutedEventArgs e)
        {
            if (LoginFrame.Visibility == Visibility.Visible)
                return;
            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Visible;
            PlayFrame.Visibility = Visibility.Hidden;
            SelectTabUser();
        }
        public virtual void OnTabPlay(object sender, RoutedEventArgs e)
        {
            if (LoginFrame.Visibility == Visibility.Visible)
                return;
            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Hidden;
            PlayFrame.Visibility = Visibility.Visible;
            SelectTabPlay();
        }
        public virtual void OnClosePlay(object sender, RoutedEventArgs e)
        {
            MediaPlayerPage page = PlayFrame.Content as MediaPlayerPage;
            if (page == null)
                return;

            TabPlay.HideTab();
            OnTabUser(sender, e);
            page.Stop();
        }
        public virtual void OnLogout(object sender, RoutedEventArgs e)
        {

            LoginFrame.Visibility = Visibility.Visible;
            MainFrame.Visibility = Visibility.Hidden;
            PlayFrame.Visibility = Visibility.Hidden;
            MediaPlayerPage page = PlayFrame.Content as MediaPlayerPage;
            TabUser.Text = "Login to Google";

            HideExpand();
            System.Windows.Application curApp = System.Windows.Application.Current;
            curApp.Shutdown();
        }
        private void ChangeToClient(object sender, RoutedEventArgs e)
        {
            if (IsServer == false)
                return;
            if (LoginFrame.Visibility == Visibility.Hidden)
            {
                OnLogout(sender, e);
            }
            TitleText.Text = "Home Media Browser";
            GoogleLoginPage LoginPage = LoginFrame.Content as GoogleLoginPage;
            LoginPage.SetPageTyle(false);
            IsServer = false;
        }
        private void ChangeToServer(object sender, RoutedEventArgs e)
        {
            string ServerPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "HomeDaemon.exe";
            IntPtr result = NativeMethods.ShellExecuteW((IntPtr)0, "open", ServerPath, null, null, 1 /* SW_SHOWNORMAL */);

            if (IsServer == true)
                return;
            if (LoginFrame.Visibility == Visibility.Hidden)
            {
                OnLogout(sender, e);
            }
            TitleText.Text = "Home Server Panel";
            GoogleLoginPage LoginPage = LoginFrame.Content as GoogleLoginPage;
            LoginPage.SetPageTyle(true);
            IsServer = true;
        }
        private void ShowServerStatus(object sender, RoutedEventArgs e)
        {
            MainPanel Panel = MainFrame.Content as MainPanel;
            if (Panel != null)
                new DownloadHelper(Panel, TaskType.TASK_SERVERSTATUS, "");
        }
        private void ChangeAccount(object sender, RoutedEventArgs e)
        {
            if (LoginFrame.Visibility == Visibility.Hidden)
            {
                OnLogout(sender, e);
            }
        }
        public Boolean IsServer;

        private string Encode64(string Message)
        {
            char[] Base64Code = new char[] 
              { 
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
                  'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 
                  'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 
                  'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', 
                  '4', '5', '6', '7', '8', '9', '+', '/', '=' 
              };
            byte empty = (byte)0;
            System.Collections.ArrayList byteMessage = new
              System.Collections.ArrayList(System.Text.Encoding.UTF8.GetBytes
              (Message));
            System.Text.StringBuilder outmessage;
            int messageLen = byteMessage.Count;
            int page = messageLen / 3;
            int use = 0;
            if ((use = messageLen % 3) > 0)
            {
                for (int i = 0; i < 3 - use; i++)
                    byteMessage.Add(empty);
                page++;
            }
            outmessage = new System.Text.StringBuilder(page * 4);
            for (int i = 0; i < page; i++)
            {
                byte[] instr = new byte[3];
                instr[0] = (byte)byteMessage[i * 3];
                instr[1] = (byte)byteMessage[i * 3 + 1];
                instr[2] = (byte)byteMessage[i * 3 + 2];
                int[] outstr = new int[4];
                outstr[0] = instr[0] >> 2;
                outstr[1] = ((instr[0] & 0x03) << 4) ^ (instr[1] >> 4);
                if (!instr[1].Equals(empty))
                    outstr[2] = ((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6);
                else
                    outstr[2] = 64;
                if (!instr[2].Equals(empty))
                    outstr[3] = (instr[2] & 0x3f);
                else
                    outstr[3] = 64;
                outmessage.Append(Base64Code[outstr[0]]);
                outmessage.Append(Base64Code[outstr[1]]);
                outmessage.Append(Base64Code[outstr[2]]);
                outmessage.Append(Base64Code[outstr[3]]);
            }
            return outmessage.ToString();
        }

        private string Decode64(string Message)
        {
            string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            int page = Message.Length / 4;
            System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3);
            char[] message = Message.ToCharArray();
            for (int i = 0; i < page; i++)
            {
                byte[] instr = new byte[4];
                instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
                instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
                instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
                instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
                byte[] outstr = new byte[3];
                outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
                if (instr[2] != 64)
                {
                    outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
                }
                else
                {
                    outstr[2] = 0;
                }
                if (instr[3] != 64)
                {
                    outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
                }
                else
                {
                    outstr[2] = 0;
                }
                outMessage.Add(outstr[0]);
                if (outstr[1] != 0)
                    outMessage.Add(outstr[1]);
                if (outstr[2] != 0)
                    outMessage.Add(outstr[2]);
            }
            byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
            return System.Text.Encoding.UTF8.GetString(outbyte);
        }


        private void OnExpanderDown(object sender, RoutedEventArgs e)
        {
            if (LoginFrame.Visibility == Visibility.Visible)
                return;
            ExpanderDown.Visibility = Visibility.Hidden;
            ExpanderUp.Visibility = Visibility.Visible;

            //Storyboard ExpanderDSB = new Storyboard();
            //Duration Dur = new Duration(new TimeSpan(0,0,0,0,300));
            //DoubleAnimation WindowHeightAnimation = new DoubleAnimation(605,Dur);
            //Storyboard.SetTarget(WindowHeightAnimation, this);
            //Storyboard.SetTargetProperty(WindowHeightAnimation, new PropertyPath(Window.HeightProperty));
            //ExpanderDSB.Children.Add(WindowHeightAnimation);
            //ExpanderDSB.Begin();

            if (WindowHeightTimer != null)
            {
                WindowHeightTimer.Stop();
            }

            WindowHeightTimer = new DispatcherTimer();
            WindowHeightTimer.Interval = new TimeSpan(0, 0, 0, 0, 30);   //0.1s

            if (MainCanvas.Height - 485 < WindowHeightAnimation)
            {
                WindowHeightTimer.Tick += new EventHandler(WindowHeightDown_Tick);
                WindowHeightTimer.Start();
            }
            else
            {
                WindowHeightTimer.Tick += new EventHandler(WindowHeightDown_Tick);
                WindowHeightTimer.Start();
            }
        }
        private void OnExpanderUp(object sender, RoutedEventArgs e)
        {
            ExpanderDown.Visibility = Visibility.Visible;
            ExpanderUp.Visibility = Visibility.Hidden;

            //Storyboard ExpanderDSB = new Storyboard();
            //Duration Dur = new Duration(new TimeSpan(0, 0, 0, 0, 300));
            //DoubleAnimation WindowHeightAnimation = new DoubleAnimation(485, Dur);
            //Storyboard.SetTarget(WindowHeightAnimation, this);
            //Storyboard.SetTargetProperty(WindowHeightAnimation, new PropertyPath(Window.HeightProperty));
            //ExpanderDSB.Children.Add(WindowHeightAnimation);
            //ExpanderDSB.Begin();
            if (WindowHeightTimer != null)
            {
                WindowHeightTimer.Stop();
            }

            WindowHeightTimer = new DispatcherTimer();
            WindowHeightTimer.Interval = new TimeSpan(0, 0, 0, 0, 30);   //0.1s

            if (MainCanvas.Height - 485 < WindowHeightAnimation)
            {
                WindowHeightTimer.Tick += new EventHandler(WindowHeightUp_Tick);
                WindowHeightTimer.Start();
            }
            else
            {
                WindowHeightTimer.Tick += new EventHandler(WindowHeightUp_Tick);
                WindowHeightTimer.Start();
            }
        }

        private void WindowHeightDown_Tick(object sender, EventArgs e)
        {
            double OneHeight = WindowHeightAnimation * 0.1 / 0.6;//DispatcherTimer 0.05s,Total 1s
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            tagRECT rcWindow = new tagRECT();
            GetWindowRect(hwnd, out rcWindow);

            CanvasExpander.Height += OneHeight;
            if (CanvasExpander.Height >= WindowHeightAnimation )
                CanvasExpander.Height = WindowHeightAnimation ;

            if (WindowHeightAnimationCurrent >= WindowHeightAnimation)
            {
                OneHeight = 0;
                if (WindowHeightTimer != null)
                    WindowHeightTimer.Stop();
                //CanvasExpander.Opacity = 100;
                CanvasExpander.Height = WindowHeightAnimation ;
            }
            Thickness BottomMargin = CanvasFrame.Margin;
            BottomMargin.Bottom = 45 + CanvasExpander.Height;
            BottomMargin.Top = 60;
            LoginFrame.Margin = BottomMargin;
            MainFrame.Margin = BottomMargin;
            PlayFrame.Margin = BottomMargin;

            SetWindowPos(hwnd, IntPtr.Zero, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top + (int)OneHeight, 0);
            WindowHeightAnimationCurrent += OneHeight;
            UpdateLayout();
        }
        private void WindowHeightUp_Tick(object sender, EventArgs e)
        {
            double OneHeight = WindowHeightAnimation * 0.1 / 0.6;//DispatcherTimer 0.05s,Total 1s
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            tagRECT rcWindow = new tagRECT();
            GetWindowRect(hwnd, out rcWindow);

            if (CanvasExpander.Height - OneHeight < 0)
                CanvasExpander.Height = OneHeight;
            CanvasExpander.Height -= OneHeight;

            if (WindowHeightAnimationCurrent <= 0)
            {
                OneHeight = 0;
                if (WindowHeightTimer != null)
                    WindowHeightTimer.Stop();
                //CanvasExpander.Opacity = 0;
                CanvasExpander.Height = 0;
            }
            Thickness BottomMargin = CanvasFrame.Margin;
            BottomMargin.Bottom = 45 + CanvasExpander.Height;
            BottomMargin.Top = 60;
            LoginFrame.Margin = BottomMargin;
            MainFrame.Margin = BottomMargin;
            PlayFrame.Margin = BottomMargin;

            SetWindowPos(hwnd, IntPtr.Zero, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top - (int)OneHeight, 0);
            WindowHeightAnimationCurrent -= OneHeight;
            UpdateLayout();
        }
        //animation param.
        private double WindowHeightAnimation;
        private double WindowHeightAnimationCurrent;
        private DispatcherTimer WindowHeightTimer;
        //private double CanvasExpanderButtonHeight;
        private void ShowExpand()
        {
            if (Height > 485)
            {
                ExpanderDown.Visibility = Visibility.Hidden;
                ExpanderUp.Visibility = Visibility.Visible;
            }
            else
            {
                ExpanderDown.Visibility = Visibility.Visible;
                ExpanderUp.Visibility = Visibility.Hidden;
            }
        }

        private void HideExpand()
        {
            OnExpanderUp(null,null);

            ExpanderDown.Visibility = Visibility.Hidden;
            ExpanderUp.Visibility = Visibility.Hidden;

        }

        public MainPanel GetMainPanel()
        {
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;
            return Panel;
        }
        public DownloadPage GetDownloadPage()
        {
            object cont = DownloadFrame.Content;
            DownloadPage Panel = cont as DownloadPage;
            return Panel;
        }

        public void DefaultLogin()
        {
            //modify it doesn't default login ,it just show log in ui. 
            LoginFrame.Visibility = Visibility.Visible;
            MainFrame.Visibility = Visibility.Hidden;
            PlayFrame.Visibility = Visibility.Hidden;
            MediaPlayerPage page = PlayFrame.Content as MediaPlayerPage;
            TabUser.Text = "Login to Google";
            GoogleLoginPage LoginPage = LoginFrame.Content as GoogleLoginPage;
            LoginPage.SetPageTyle(IsServer);
            if (IsServer)
            {
                string ServerPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "HomeDaemon.exe";
                IntPtr Shellresult = NativeMethods.ShellExecuteW((IntPtr)0, "open", ServerPath, null, null, 1 /* SW_SHOWNORMAL */);

            }
            return;

            HideExpand();
            LoginFrame.Visibility = Visibility.Hidden;
            MainFrame.Visibility = Visibility.Visible;
            PlayFrame.Visibility = Visibility.Hidden;
            object cont = MainFrame.Content;
            MainPanel Panel = cont as MainPanel;
         //   return;
            int result = GoogleLoginPage.LogIn(null,null);
            if (result <= 0)
            {
                //LoginForm LF = new LoginForm();
                //DialogResult DResult = LF.ShowDialog();
                //while (DResult != System.Windows.Forms.DialogResult.OK)
                //{
                //    if (DResult == System.Windows.Forms.DialogResult.Cancel)
                //    {
                //        App.Current.Shutdown();
                //        return;
                //    }
                //}
                OnLogout(null, null);
                return;
            }
            StringBuilder strUserName = new StringBuilder(1000);
            GoogleLoginPage.GetAccountId(strUserName);
            StringBuilder strPassword = new StringBuilder(1000);
            GoogleLoginPage.GetAccountPwd(strPassword);

            TabUser.Text = strUserName.ToString();

            if (IsServer == false)
            {
                string strEntryName = "HomeMediaServer";
                StringBuilder strIpAddr = new StringBuilder(128);
                GoogleLoginPage.GetIP(strEntryName,strIpAddr);

                Panel.ServerIP = strIpAddr.ToString();
                TitleText.Text = "Home Media Browser";
                Panel.InitServer(IsServer);
                ShowExpand();
                ServerStatusButton.Visibility = Visibility.Hidden;
            }
            else
            {
                string ServerPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "HomeDaemon.exe";
                IntPtr Shellresult = NativeMethods.ShellExecuteW((IntPtr)0, "open", ServerPath, null, null, 1 /* SW_SHOWNORMAL */);

                Panel.ServerIP = "http://127.0.0.1:8080/";
                GoogleLoginPage.SetPublicIP("http://127.0.0.1:8080/",strUserName.ToString(),strPassword.ToString());

                TitleText.Text = "Home Server Panel";
                Panel.InitServer(IsServer);
                HideExpand();
                ServerStatusButton.Visibility = Visibility.Visible;
            }
        }
        private void OnServerStatus(object sender, RoutedEventArgs e)
        {
            ShowServerStatus(sender, e);
        }
    }
}
